
<!-- 文件路径: src/views/Recommendation.vue -->
<template>
  <div class="recommendation-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个性化推荐</span>
          <el-button type="primary" :disabled="loading" @click="fetchRecommendations">刷新推荐</el-button>
        </div>
      </template>

      <el-alert v-if="error" :title="error" type="error" show-icon class="recommendation-alert" />
      <el-empty v-if="!loading && recommendations.length === 0" description="暂无推荐房源" />

      <el-table :data="paginatedRecommendations" style="width: 100%" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="district" label="行政区" />
        <el-table-column prop="sub_district" label="商圈" />
        <el-table-column prop="avg_unit_price" label="平均单价 (万元/㎡)" />
        <el-table-column label="推荐理由">
          <template #default="{ row }">
            <el-tooltip :content="row.reason" placement="top">
              <span>{{ row.reason.slice(0, 20) + (row.reason.length > 20 ? '...' : '') }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetails(row)">查看详情</el-button>
            <el-button size="small" type="success" @click="addToFavorites(row)">收藏</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="totalItems > pageSize"
        background
        layout="prev, pager, next"
        :total="totalItems"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handlePageChange"
        style="margin-top: 20px;"
      />
    </el-card>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useFootprintStore } from '@/stores/footprints';
import { useAuthStore } from '@/stores/auth';
import { ElMessage } from 'element-plus';
import Papa from 'papaparse';
import {Back} from "@element-plus/icons-vue";

const router = useRouter();
const footprintStore = useFootprintStore();
const authStore = useAuthStore();

const deepseekApiKey = 'sk-955e728f2a3a4d51bbdef9cd5400cb38'; // 替换为你的实际 DeepSeek API Key

const loading = ref(false);
const error = ref('');
const recommendations = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const totalItems = ref(0);
const propertyList = ref([]);

const paginatedRecommendations = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return recommendations.value.slice(start, start + pageSize.value);
});

const loadCsvData = async () => {
  try {
    const response = await fetch('/assets/properties.csv');
    if (!response.ok) {
      throw new Error(`加载 CSV 文件失败: ${response.statusText}`);
    }
    const csvText = await response.text();
    Papa.parse(csvText, {
      header: true,
      skipEmptyLines: true,
      complete: (result) => {
        if (result.errors.length) {
          throw new Error('CSV 解析失败: ' + result.errors[0].message);
        }
        propertyList.value = result.data.map(item => ({
          id: parseInt(item.id, 10),
          name: item.小区 || '',
          district: item.区域 || '',
          sub_district: item.商圈 || '',
          avg_unit_price: parseFloat(item.单价平均价格) || 0,
          avg_total_price: parseFloat(item.总价平均价格) || 0,
          longitude: parseFloat(item.longitude) || 0,
          latitude: parseFloat(item.latitude) || 0,
          listing_year: parseInt(item.挂牌年份, 10) || 0,
          listing_month: item.挂牌月份 || ''
        }));
        console.log('CSV 解析完成，房源数量:', propertyList.value.length);
        console.log('样本数据:', propertyList.value.slice(0, 5));
      },
      error: (error) => {
        throw new Error('CSV 解析错误: ' + error.message);
      }
    });
  } catch (err) {
    error.value = '加载 CSV 数据失败: ' + err.message;
    console.error('CSV 加载错误:', err);
    ElMessage.error(error.value);
  }
};

const fetchRecommendations = async () => {
  if (!authStore.isAuthenticated || !authStore.getApiKey) {
    ElMessage.warning('请先登录并获取系统 API Key');
    return;
  }
  if (!deepseekApiKey) {
    ElMessage.warning('DeepSeek API Key 未配置');
    return;
  }
  if (propertyList.value.length === 0) {
    ElMessage.warning('房源数据未加载，请检查 CSV 文件');
    return;
  }

  loading.value = true;
  error.value = '';
  console.log('System API Key:', authStore.getApiKey);
  console.log('DeepSeek API Key:', deepseekApiKey);
  console.log('Loading state:', loading.value);

  try {
    if (footprintStore.footprints.length === 0) {
      await footprintStore.fetchFootprints();
      console.log('Footprints loaded:', footprintStore.footprints.length);
    }

    const collectedFootprints = footprintStore.footprints.map(fp => ({
      id: fp.property.id,
      rating: fp.rating || 0,
      comment: fp.notes || '暂无评论'
    }));

    const availableProperties = propertyList.value
      .filter(prop => !collectedFootprints.some(fp => fp.id === prop.id))
      .sort(() => Math.random() - 0.5)
      .slice(0, 1000)
      .map(prop => ({
        id: prop.id,
        name: prop.name,
        district: prop.district,
        sub_district: prop.sub_district,
        avg_unit_price: prop.avg_unit_price,
        avg_total_price: prop.avg_total_price,
        longitude: prop.longitude,
        latitude: prop.latitude
      }));

    const userPreferences = collectedFootprints.map(col => {
      const prop = propertyList.value.find(p => p.id === col.id);
      return `- 房源ID ${col.id}: 区域 ${prop?.district || '未知'}, 商圈 ${prop?.sub_district || '未知'}, 单价 ${prop?.avg_unit_price?.toFixed(2) || 0}万元/㎡, 评分 ${col.rating}, 评论 "${col.comment}"`;
    }).join('\n');

    const prompt = `
      你是一个房地产推荐专家。以下是用户收藏的房源及其信息：
      ${userPreferences}
      基于用户偏好（优先考虑评分高、评论好、价格合理的房源），从以下房源列表中推荐10个未收藏的房源（排除ID为 ${collectedFootprints.map(c => c.id).join(', ')} 的房源）：
      ${JSON.stringify(availableProperties)}
      推荐时综合分析用户对房源的核心需求，推荐时考虑区域、商圈、单价、以及周围环境、配套设施的相似性，并提供逻辑清晰的推荐理由，尽量不要重复。
      以 JSON 格式返回结果，格式为：{ "recommendations": [{"id": number, "reason": string}, ...], "total": number }
    `;
    console.log('Prompt length:', prompt.length);
    console.log('Prompt sample:', prompt.slice(0, 200) + '...');

    const fetchWithRetry = async (url, options, retries = 3) => {
      for (let i = 0; i < retries; i++) {
        try {
          const response = await fetch(url, options);
          if (!response.ok) {
            const errorData = await response.json().catch(() => response.statusText);
            if (response.status === 429) {
              throw new Error('DeepSeek API 配额已用尽，请稍后重试或联系管理员');
            }
            if (response.status === 401) {
              throw new Error('DeepSeek API Key 无效，请检查配置');
            }
            throw new Error(`API 请求失败: ${JSON.stringify(errorData)}`);
          }
          return await response.json();
        } catch (error) {
          console.error(`DeepSeek API 请求失败 (${i + 1}/${retries}):`, error.message);
          if (i < retries - 1) {
            console.log(`重试 DeepSeek API 请求 (${i + 1}/${retries})`);
            await new Promise(resolve => setTimeout(resolve, 2000));
            continue;
          }
          throw error;
        }
      }
    };

    const data = await fetchWithRetry('https://api.deepseek.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${deepseekApiKey}`
      },
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: [
          { role: 'system', content: 'You are a helpful assistant.' },
          { role: 'user', content: prompt }
        ],
        stream: false,
        max_tokens: 1500,
        temperature: 0.7,
        response_format: { type: 'json_object' }
      })
    });

    console.log('Raw Response:', data);
    const result = JSON.parse(data.choices[0].message.content);
    recommendations.value = result.recommendations || [];
    totalItems.value = result.total || recommendations.value.length;

    const recommendedIds = recommendations.value.map(r => r.id);
    const fullRecommendations = propertyList.value.filter(prop => recommendedIds.includes(prop.id));
    recommendations.value = fullRecommendations.map(prop => {
      const rec = recommendations.value.find(r => r.id === prop.id);
      return { ...prop, reason: rec?.reason || '无推荐理由' };
    });
    console.log('Recommendations fetched:', recommendations.value.length);
    console.log('Recommended IDs:', recommendedIds);
  } catch (err) {
    error.value = `推荐获取失败: ${err.message || '未知错误'}`;
    console.error('API Error:', err);
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};

const viewDetails = (row) => {
  // 确保传递完整的房源数据
  console.log('Navigating to details with row:', row); // 调试
  router.push({
    path: '/recommendations/:id',
    query: {
      propertyId: row.id,
      name: encodeURIComponent(row.name || ''),
      district: encodeURIComponent(row.district || ''),
      sub_district: encodeURIComponent(row.sub_district || ''),
      avg_unit_price: row.avg_unit_price || 0,
      avg_total_price: row.avg_total_price || 0,
      longitude: row.longitude || 0,
      latitude: row.latitude || 0,
      listing_year: row.listing_year || 0,
      listing_month: encodeURIComponent(row.listing_month || ''),
      reason: encodeURIComponent(row.reason || '')
    }
  });
};

const addToFavorites = async (row) => {
  try {
    await footprintStore.addFootprint(row.id);
    ElMessage.success('已添加到收藏');
    await footprintStore.fetchFootprints();
  } catch (err) {
    ElMessage.error('收藏失败: ' + err.message);
  }
};

const handleExit = async () => {
  await router.push('/profile');
};

onMounted(async () => {
  if (!authStore.statusChecked) {
    await authStore.checkAuthStatus(true);
  }
  if (authStore.isAuthenticated && authStore.getApiKey) {
    await loadCsvData();
    await footprintStore.fetchFootprints();
    console.log('Initial footprints loaded:', footprintStore.footprints.length);
  } else {
    ElMessage.warning('请先登录并获取系统 API Key');
  }
});
</script>

<style scoped>
.recommendation-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommendation-alert {
  margin-bottom: 20px;
}

.bottom-right-button {
  position: fixed;
  right: 40px;
  bottom: 40px;
  z-index: 10;
}
</style>
